<template>
  <div>
    <!-- 搜索结果页-头部导航 -->
    <div class="search-result-container">
      <!-- 点击实现后退效果 -->
      <van-nav-bar
        title="搜索结果"
        left-arrow
        @click-left="$router.go(-1)"
        fixed
      />
      <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
          :immediate-check="false"
          offset="50"
        >
          <ArticleItem
            v-for="(item, index) in articlesList"
            :key="item.art_id + index"
            :obj="item"
            :showX="false"
             @click.native="$router.push(`/article_detail?aid=${item.art_id}`)"
          >
          </ArticleItem>
        </van-list>
      </van-pull-refresh>
    </div>
  </div>
</template>

<script>
import { searchResultListAPI } from '@/api'
import { timeAgo } from '@/utils/day.js'
import ArticleItem from '@/views/Home/components/ArticleItem'
export default {
  name: 'SearchResult',
  data () {
    return {
      articlesList: [],
      page: 1,
      finished: false,
      loading: false,
      isLoading: false
    }
  },
  methods: {
    timeAgo: timeAgo,
    onLoad () {
      if (this.articlesList.length > 0) {
        this.page++
        this.getarticlesList()
      }
    },
    onRefresh () {
      this.getarticlesList()
      this.isLoading = false
    },
    async getarticlesList () {
      const res = await searchResultListAPI({
        q: this.$route.params.keywords,
        page: this.page
      })

      res.data.data.results.forEach((item) => {
        item.pubdate = this.timeAgo(item.pubdate)
      })
      // this.articlesList = res.data.data.results
      // 如果无数据
      if (res.data.data.results.length === 0) {
        this.finished = true // 告诉list组件直接底部显示没有更多数据
      } else {
        this.articlesList = [...this.articlesList, ...res.data.data.results]
        // 等待网络请求结果后
        this.loading = false // 底部加载更多状态
      }
    }
  },
  async created () {
    this.getarticlesList()
    // const res = await searchResultListAPI({ q: this.$route.params.keywords })
    // console.log(res)
    // this.articlesList = res.data.data.results
  },
  components: {
    ArticleItem
  }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
@nav-bar-icon-color: white;
</style>
